import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import * as API from '../api/http'

const initialState = {
    shoplist:[]
}

const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    getshoplist(state, action) {
        state.shoplist=action.payload
    },

        delshoplist(state, action) {
        state.shoplist=state.shoplist.filter(item=>{
            return item.id !== action.payload
        })
    },

        addshoplist(state, action) {
        state.shoplist.push(action.payload)
    },

        editshoplist(state, action) {
            let i = state.shoplist.findIndex(item=>{
                return item.id == action.payload.id
            })
            state.shoplist[i] = action.payload
    },

  },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;

export const async_getshoplist = createAsyncThunk('async_getshoplist',
    async(_,store)=>{
        const res = await API.getshoplist()
        store.dispatch(actionfn.getshoplist(res))
    })

    export const async_delshoplist = createAsyncThunk('async_delshoplist',
    async(id,store)=>{
        await API.delshoplist(id)
        store.dispatch(actionfn.delshoplist(id))
    })

    export const async_addshoplist = createAsyncThunk('async_addshoplist',
    async(obj,store)=>{
        const res = await API.addshoplist(obj)
        store.dispatch(actionfn.addshoplist(res))
    })

    export const async_editshoplist = createAsyncThunk('async_editshoplist',
    async(obj,store)=>{
        const res = await API.editshoplist(obj)
        store.dispatch(actionfn.editshoplist(res))
    })